<template>
  <div class="right-top-wrap">
    <visual-operation class="tool-item" />
    <micro-gas class="tool-item" />
    <zero-gas class="tool-item" />
    <negative-gas class="tool-item" />
    <meter-quality class="tool-item" />
    <Button class="tool-item" type="info" size="small" @click="handleMeterDetail">表具详情</Button>
    <right-top-type class="tool-item" style="width: 120px" />
    <Button
      class="tool-item"
      type="primary"
      size="small"
      @click="handleSave"
      :loading="saveLoading"
      :disabled="btnDisabled"
      >保存</Button
    >
    <Button type="info" size="small" @click="handleLoad" :loading="loadLoading" :disabled="btnDisabled">加载</Button>
    <Tooltip placement="top" transfer>
        <Icon type="md-help-circle help-icon" />
        <div slot="content">
            <p>功能快捷键提示：</p>
            <p>
              线性拟合: ctrl + q
            </p>
        </div>
    </Tooltip>

    <!-- 表具详情 -->
    <Modal
      v-model="showMeterAndUserInfo"
      :title="currentMeterId + ' 表具详情'"
      @on-cancel="handleMeterAndUserInfoClose"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div
        id="meterAndUserInfo"
        :is="userAndMeterInfoTpl"
        :currentMeterId="currentMeterId"
        :content="meterAndUserInfo"
      ></div>
      <div slot="footer">
        <Button @click="handleMeterAndUserInfoClose" ghost>关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { each, isNaN } from 'lodash'
import { createNamespacedHelpers } from 'vuex'
import MicroGas from '../MicroGas'
import ZeroGas from '../ZeroGas'
import NegativeGas from '../NegativeGas'
import VisualOperation from '../VisualOperation'
import MeterQuality from '../MeterQuality'
import RightTopType from '../RightTopType'

const { mapState, mapActions } = createNamespacedHelpers('historyVerify')

export default {
  name: 'history-verify-right-top',
  components: {
    MicroGas,
    ZeroGas,
    NegativeGas,
    VisualOperation,
    MeterQuality,
    RightTopType,
    UserAndMeterDetailETree: () => import('@/commons/UserAndMeterDetailETree')
  },
  data() {
    return {
      showMeterAndUserInfo: false,
      userAndMeterInfoTpl: null,
      meterAndUserInfo: null,
      saveLoading: false,
      loadLoading: false
    }
  },
  computed: {
    ...mapState([
      'currentMeterId',
      'hasRemoveSolid',
      'qcycstForm',
      'currentType',
      'hasRemoveLines',
      'byxs',
      'xxlhList',
      'xxlhParams',
      'selectedTableRow',
      'tableData',
      'loadState'
    ]),
    btnDisabled() {
      return this.currentMeterId == null
    }
  },
  methods: {
    ...mapActions([
      'loadMeterDetail',
      'changeStopTableKeyUp',
      'saveParams',
      'loadLoadData',
      'changeCurrentType',
      'changeXxlhList',
      'changeXxlhParams',
      'changeHasRemoveLines',
      'changeHasRemoveSolid',
      'changeQCYCSTFrom',
      'changeByxs',
      'changeXxlhState',
      'changeLoadState'
    ]),
    handleMeterAndUserInfoClose() {
      this.changeStopTableKeyUp(false)
      this.showMeterAndUserInfo = false
      this.userAndMeterInfoTpl = null
      this.meterAndUserInfo = null
    },
    async handleMeterDetail() {
      if (!this.currentMeterId) {
        return this.$Notice.warning({
          title: '操作提示',
          desc: '没有可操作的数据'
        })
      }
      this.changeStopTableKeyUp(true)
      const { code, date } = await this.loadMeterDetail()
      if (code === 200) {
        this.meterAndUserInfo = date
        this.userAndMeterInfoTpl = 'UserAndMeterDetailETree'
        this.showMeterAndUserInfo = true
      }
    },
    async handleSave() {
      if (this.currentType == null) {
        return this.$Notice.warning({
          title: '操作提示',
          desc: '没有选择类型'
        })
      }
      const _linearFitting = []
      each(this.xxlhParams, (item, index) => {
        _linearFitting.push({
          ...item,
          data: JSON.stringify(this.xxlhList[index])
        })
      })
      const _data = {
        isAbnormalEntity: this.hasRemoveSolid,
        maxUsageAll: this.qcycstForm.max,
        minUsageAll: this.qcycstForm.min,
        exceptionTypes: this.currentType,
        isDownLead: this.hasRemoveLines,
        linearFitting: _linearFitting
      }
      const _byxs = this.byxs
      if (_byxs != null && !isNaN(parseFloat(_byxs))) {
        _data.variableCoefficient = parseFloat(_byxs)
      }
      this.saveLoading = true
      const { code, msg } = await this.saveParams(_data)
      this.saveLoading = false
      if (code === 200) {
        this.$Message.success(msg)
      } else {
        this.$Message.error(msg)
      }
    },
    async handleLoad() {
      this.loadLoading = true
      const { code, date } = await this.loadLoadData()
      this.loadLoading = false
      if (code === 200) {
        this.changeLoadState(!this.loadState)
        this.modifyLoadData(date)
      } else {
        this.$Message.error('加载失败')
      }
    },
    modifyLoadData(data) {
      const {
        isAbnormalEntity,
        maxUsageAll,
        minUsageAll,
        exceptionTypes,
        isDownLead,
        variableCoefficient,
        linearFitting = []
      } = data
      this.changeHasRemoveSolid(!!isAbnormalEntity)
      this.changeQCYCSTFrom({
        min: minUsageAll,
        max: maxUsageAll
      })
      this.changeCurrentType(exceptionTypes)
      this.changeHasRemoveLines(!!isDownLead)
      let _byxs = variableCoefficient
      if (_byxs && _byxs > 0) {
        _byxs = `${_byxs}%`
      }
      this.changeByxs(_byxs)
      const _row = this.selectedTableRow == null ? null : this.tableData.list[this.selectedTableRow]
      this.modifyTagNav(_row, _byxs)
      if (linearFitting.length > 0) {
        this.changeXxlhState(true)
        const _paramsList = []
        const _xxlhList = []
        each(linearFitting, item => {
          const { data, ...rest } = item
          _paramsList.push(rest)
          try {
            _xxlhList.push(JSON.parse(data))
          } catch (error) {
            // do nothing
          }
        })
        this.changeXxlhList(_xxlhList)
        this.changeXxlhParams(_paramsList)
      } else {
        this.changeXxlhState(false)
      }
    },
    modifyTagNav(row, byxs = null) {
      const { unitName, meterId } = row
      const _newList = []
      each(this.$store.state.app.tagNavList, item => {
        const { name, meta = {}, ...rest } = item
        if (name === 'history-verify') {
          const _first = meta.title && meta.title.split('(')[0]
          meta.title = `${_first}(${unitName} ${meterId}；变异系数 ${byxs})`
          _newList.push({
            name,
            meta,
            ...rest
          })
        } else {
          _newList.push(item)
        }
      })
      this.$store.commit('setTagNavList', _newList)
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';

.right-top-wrap {
  width: 100%;
  height: 100%;

  @{deep} .ivu-select-dropdown {
    z-index: 9999;
  }

  .tool-item {
    display: inline-block;
    margin-right: 10px;
  }

  .help-icon {
    font-size: 20px;
    margin-left: 10px;
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>
